﻿using CPPEI.WebApi;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace CMS.WebApi.Media
{
    [AuthPostAction("media", "create", "1.0")]
    public class CreateAction : BaseAction<CreateParams, CreateResult>
    {
        protected override ActionResult<CreateResult> OnExecute(ActionContext context, SysParams sysParams, CreateParams opParams)
        {
            string tempFilePath = HttpContext.Current.Server.MapPath(opParams.RelativeFilePath);
            string extension = GetExtension(tempFilePath);
            string url = string.Format("_content/media/{0}.{1}", opParams.Id.ToString(), extension);
            string filePath = HttpContext.Current.Server.MapPath(string.Format("~/{0}", url));

            FileInfo fileInfo = new FileInfo(filePath);
            if(fileInfo.Directory.Exists == false)
            {
                fileInfo.Directory.Create();
            }

            File.Move(tempFilePath, filePath);

            CMS.Domain.Services.CreateService service = new Domain.Services.CreateService();

            CPPEI.ServiceResult serResult = service.CreateMedia(Guid.Empty, opParams.Id, url, filePath, opParams.Description, context.UserId);

            if(serResult.IsSuccess)
            {
                CreateResult actResult = new CreateResult();
                return new ActionResult<CreateResult>(actResult);
            }
            else
            {
                // 删除文件
                File.Delete(filePath);
                return new ActionResult<CreateResult>(serResult);
            }
        }
        private string GetExtension(string fileName)
        {
            string[] fileSegments = fileName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
            if (fileSegments.Length == 0)
            {
                return string.Empty;
            }
            return fileSegments.Last();
        }
    }

    public class CreateParams
    {
        public Guid Id { get; set; }
        public string RelativeFilePath { get; set; }
        public Guid FolderId { get; set; }
        public string Description { get; set; }
    }

    public class CreateResult
    {
    }
}
